#include "chat.h"

void* share_memory = NULL;
void print(int signum){
    pthread_mutex_lock(&((struct Msg*)share_memory)->mutex);
    printf("%s : %s\n", ((struct Msg*)share_memory)->name, ((struct Msg*)share_memory)->msg);
    memset(((struct Msg*)share_memory)->msg, 0, sizeof((struct Msg*)share_memory)->msg);
    pthread_mutex_unlock(&((struct Msg*)share_memory)->mutex);
}

int main(){
    key_t key = ftok(".", 20210106);
    int shmid;
    if((shmid = shmget(key, sizeof(struct Msg), IPC_CREAT | 0666)) < 0){
        perror("shmget");
        exit(1);
    }

    if((share_memory = shmat(shmid, NULL, 0)) == (void*)-1){
        perror("shmat");
        exit(1);
    }

    struct Msg* message = (struct Msg*)share_memory;
    memset(message, 0, sizeof(struct Msg));
    pthread_mutexattr_t attr;
    pthread_mutexattr_init(&attr);
    pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
    pthread_mutex_init(&message->mutex, &attr);

    message->server_pid = getpid();
    //char temp[] = "server";
    //strcpy(message->name, temp);
    signal(SIGUSR1, print);

    while(1){
        sleep(10);
    }
    return 0;
}